<template>
  <div class="login-container">
    <van-nav-bar
      class="app-nav-bar"
      title="登陆"
      left-arrow
      @click-left="$router.back()"
    />
    <!-- 表单 -->
    <van-form
      @submit="onLogin"
      :show-error="false"
      :show-error-message="false"
      ref="login-form"
      @failed="onFailed"
      :validate-first="true"
    >
      <van-field
        v-model="user.mobile"
        icon-prefix="icon"
        left-icon="shouji"
        center
        placeholder="请输入手机号"
        name="mobile2"
        :rules="formRules.mobile"
      />
      <van-field
        v-model="user.code"
        clearable
        center
        icon-prefix="icon"
        left-icon="yanzhengma"
        placeholder="请输入验证码"
        :rules="formRules.code"
      >
        <template #button>
          <van-count-down
            v-if="isCountDownShow"
            :time="60 * 1000"
            format="ss 秒"
            @finish="isCountDownShow = false"
          />
          <van-button
            v-else
            size="mini"
            round
            class="sendMa"
            @click.prevent= "onSendSms"
            :loading= "isSendSmsLoading"
            >发送验证码</van-button
          >
        </template>
      </van-field>
      <div class="login-btn-wrap">
        <van-button class="login-btn" type="info" block>
          登陆
        </van-button>
      </div>
    </van-form>
  </div>
</template>
<script>
/* 在组件中可以直接通过 this.$toast 调用，这里引入了则可以直接简写用Toast */
import { login, sendSms } from "@/api/user";
import { Toast } from "vant";
export default {
  name: "LoginIndex",

  components: {},

  directives: {},

  data() {
    return {
      user: {
        mobile: "",
        code: ""
      },
      formRules: {
        mobile: [
          { required: true, message: "请填写手机号" },
          { pattern: /^1[3578]\d{9}$/, message: "手机号码格式错误" }
        ],
        code: [
          { required: true, message: "请填写验证码" },
          { pattern: /^\d{6}$/, message: "验证码格式错误" }
        ]
      },
      //控制倒计时和发送按钮的切换状态
      isCountDownShow: false,
      //避免发送验证在慢速网络时被频繁点击，发送验证码按钮加上一个loading状态
      isSendSmsLoading: false
    };
  },

  mounted() {},

  methods: {
    async onLogin() {
      Toast.loading({
        message: "登陆中...",
        forbidClick: true,
        duration: 0
      });
      try {
       /*  const res = await login(this.user); */
       const { data: res } = await login(this.user)
        console.log(res);
        Toast.success("登陆成功");
        //将后端返回的用户登录状态（token等数据）放到Vuex容器中
        this.$store.commit('setUser', res.data)
      } catch (err) {
        Toast.fail("登陆失败,手机号或者验证码错误");
      }
    },
    onFailed(error) {
      console.log(error);
      if (error.errors[0]) {
        Toast({
          message: error.errors[0].message,
          position: "top"
        });
      }
    },
    /* 发送验证码 */
    async onSendSms() {
      try {
        //校检手机号码
        const validateResult = await this.$refs["login-form"].validate("mobile2");
        this.isSendSmsLoading = true
        console.log(validateResult);
        //验证通过，请求发送验证码
        const res = await sendSms(this.user.mobile)
        console.log(res);
        //短信发出去了，显示倒计时
        this.isCountDownShow = true
      } catch (err) {
        //try里面任何代码的错误都会进入catch
        //如果发送太频繁会报错误：Error: Request failed with status code 429，这里不能像手机格式错误那样直接打印
        let message = ''
        if (err && err.response && err.response.status === 429) {
          //发送短信失败的错误提示
          message = '发送太频繁了，请稍后重试'
        } else if (err.name === "mobile2") {
          //表单验证失败的错误提示
          message = err.message;
        } else {
          //未知错误
          message = "发送失败，请稍后重试";
        }
        console.log("获取短信验证码失败，错误：", err);
        //弹出框里提示用户
        Toast({
          message,
          position: "top"
        });
      }
      //无论发送验证码是否成功，最后都要关闭发送按钮的loading状态
      this.isSendSmsLoading = false
    }
  }
};
</script>

<style lang="less" scoped>
.login-container {
  .sendMa {
    width: 82px;
    height: 23px;
    background-color: #ededed;
    .van-button__text {
      font-size: 11px;
      color: #666;
    }
  }
  .login-btn-wrap {
    padding: 26px 16px;
    .login-btn {
      background-color: #6bd4fb;
      border: none;
      .van-button__text {
        font-size: 15px;
      }
    }
  }
}
</style>
